package com.cpms.framework.log.handler;

import com.alibaba.fastjson.JSONObject;
import com.cpms.framework.common.core.api.ResultUtil;
import com.cpms.framework.common.enums.GlobalResponseResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:  全局异常捕获，解决了@RestControllerAdvice注解捕获不到的异常，比如：路径错误的异常，
 * @author: gulang
 * @time: 2022/1/28 17:02
 */

public class ResolveException implements HandlerExceptionResolver {
    private final static Logger log = LoggerFactory.getLogger(ResolveException.class);
    private ModelAndView modelAndView = new ModelAndView();

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        try {
            log.error("捕获请求未知异常信息:{}",e);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().print(JSONObject.toJSON(ResultUtil.error(GlobalResponseResultEnum.REQUEST_HANDLER_ERROR)));
        } catch (IOException e1) {
            log.error("响应IOException异常:{}",e1);
        }
        return modelAndView;
    }
}
